<template>
    <div class="flex justify-end mt-4">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :total="total"
        :page-sizes="pageSizes"
        :layout="layout"
        :background="background"
        :small="small"
        :disabled="disabled"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
</template>

<script setup>
import { ref, watch } from 'vue'

const props = defineProps({
  // 当前页码
  page: {
    type: Number,
    default: 1
  },
  // 每页条数
  limit: {
    type: Number,
    default: 10
  },
  // 总条数
  total: {
    type: Number,
    default: 0
  },
  // 每页条数选项
  pageSizes: {
    type: Array,
    default: () => [10, 20, 50, 100]
  },
  // 组件布局
  layout: {
    type: String,
    default: 'total, sizes, prev, pager, next, jumper'
  },
  // 是否使用背景色
  background: {
    type: Boolean,
    default: true
  },
  // 是否使用小型分页
  small: {
    type: Boolean,
    default: false
  },
  // 是否禁用
  disabled: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:page', 'update:limit', 'change'])

// 当前页码
const currentPage = ref(props.page)
// 每页条数
const pageSize = ref(props.limit)

// 监听props变化
watch(() => props.page, (val) => {
  currentPage.value = val
})

watch(() => props.limit, (val) => {
  pageSize.value = val
})

// 页码改变
const handleCurrentChange = (val) => {
  emit('update:page', val)
  emitChange()
}

// 每页条数改变
const handleSizeChange = (val) => {
  emit('update:limit', val)
  // 切换每页条数时，页码重置为1
  emit('update:page', 1)
  currentPage.value = 1
  emitChange()
}

// 触发change事件
const emitChange = () => {
  emit('change', {
    page: currentPage.value,
    limit: pageSize.value
  })
}
</script>

<style scoped>
.el-pagination {
  margin: 0;
  padding: 0;
}
</style>